// const autojsUtils = require('./modules/autojs-utils');
// airtel zmw ui
"ui";

const Constant = require("./constant.js");

auto();

device.keepScreenOn();

// 之前保存的钱包
Constant.initMtnAndPin();
// let preWalletNumber = storages.create(Constant.WALLET_NAME).get(Constant.WALLET_NUMBER) || "";
// let preWalletPin = storages.create(Constant.WALLET_NAME).get(Constant.WALLET_PIN) || "";

ui.layout(
    <vertical>
        <text id="sceneName"
            w="*"
            h="auto"
            gravity="center"
            marginTop="16"
            textColor="red"
            textStyle="bold"
            textSize="16"
            text={Constant.WALLET_AIRTEL_ZMW_NAME} />

        <input id="wallet"
            marginTop="16"
            hint="请输入钱包号码, 带0开头"
            text={Constant.getMtn()}
            textSize="14" />

        <input id="pin"
            marginTop="16"
            hint="请输入钱包PIN"
            text={Constant.getPin()}
            textSize="14" />

        <input id="amount"
            marginTop="16"
            hint="请输入测试转账金额"
            text={Constant.getAmount()}
            textSize="14" />

        <button id="saveAndStartTransfer"
            marginTop="16"
            text="启动转账脚本" />

        <button id="saveAndStartBills"
            marginTop="16"
            text="启动流水脚本" />

        <button id="saveOnly"
            marginTop="10"
            text="仅保存钱包号" />

    </vertical>
);

ui.saveAndStartTransfer.click(function () {
    var name = ui.wallet.text();
    var pin = ui.pin.text();
    var amount = ui.amount.text();

    if (!name || (name.length <= 8)) {
        // main();
        toast("saveAndStartTransfer: 钱包号错误!");
        return;
    }

    if (!pin || (pin.length <= 2)) {
        // main();
        toast("saveAndStartTransfer: pin错误!");
        return;
    }

    if (!amount || (amount.length <= 0)) {
        // main();
        toast("saveAndStartTransfer: amount错误!");
        return;
    }

    // 保存本地
    Constant.setMtn(name);
    Constant.setPin(pin);
    Constant.setAmount(amount);

    toast(name + "," + pin + "," + amount + " 已启动脚本 saveAndStartTransfer-transfer");

    setTimeout(() => {
        // 启动脚本
        threads.start(function () {
            //在新线程执行的代码
            main(true);
        });
    }, 2000);
});

ui.saveAndStartBills.click(function () {
    var name = ui.wallet.text();
    var pin = ui.pin.text();
    var amount = ui.amount.text();

    if (!name || (name.length <= 8)) {
        // main();
        toast("saveAndStartBills: 钱包号错误!");
        return;
    }

    if (!pin || (pin.length <= 2)) {
        // main();
        toast("saveAndStartBills: pin错误!");
        return;
    }

    if (!amount || (amount.length <= 0)) {
        // main();
        toast("saveAndStartBills: amount错误!");
        return;
    }

    // 保存本地
    Constant.setMtn(name);
    Constant.setPin(pin);
    Constant.setAmount(amount);

    toast(name + "," + pin + "," + amount + " 已启动脚本 saveAndStartBills-bills");

    setTimeout(() => {
        // 启动脚本
        threads.start(function () {
            //在新线程执行的代码
            main(false);
        });
    }, 2000);
});

ui.saveOnly.click(function () {
    var name = ui.wallet.text();
    var pin = ui.pin.text();
    var amount = ui.amount.text();

    if (!name || (name.length <= 8)) {
        // main();
        toast("saveOnly: 钱包号错误!");
        return;
    }

    if (!pin || (pin.length <= 2)) {
        // main();
        toast("saveOnly: pin错误!");
        return;
    }

    if (!amount || (amount.length <= 0)) {
        // main();
        toast("saveOnly: amount错误!");
        return;
    }

    // 保存本地
    Constant.setMtn(name);
    Constant.setPin(pin);
    Constant.setAmount(amount);

    toast(name + "," + pin + "," + amount + " 已保存 saveOnly");
});


const BaseSmsUtil = require("./baseSmsUtil.js");
const BaseApiUrl = require("./baseApiUrl.js");
const BaseHttpUtil = require("./baseHttpUtil.js");

const AirtelZmwAppOpen = require("./airtelZmwAppOpen.js");
const AirtelZmwPageUtil = require("./airtelZmwPageUtil.js");
const AirtelZmwFunAction = require("./airtelZmwFunAction.js");


// 转账信息
let targetTransferAmount = "";
let targetTransferId = "";
let targetTransferAccount = "";
let targetTransferReference = "";

const initTransfer = (data) => {
    targetTransferAmount = data.amount + "";
    targetTransferId = data.id + "";
    targetTransferAccount = data.mtn + "";
    targetTransferReference = data.reference + "";
}

const isValidTransfer = () => {
    let result1 = targetTransferAmount || "";
    let result2 = targetTransferId || "";
    let result3 = targetTransferAccount || "";

    return ((result1.length > 0) && (result2.length > 0) && (result3.length > 0));
}

const cleanTransfer = () => {
    targetTransferAmount = "";
    targetTransferId = "";
    targetTransferAccount = "";
    targetTransferReference = "";
}

const printTransferLog = () => {
    console.log(Constant.UI_SDK_VERSION + "targetTransferAmount: " + targetTransferAmount + ",\ntargetTransferId: " + targetTransferId + ",\ntargetTransferAccount: " + targetTransferAccount + ",\ntargetTransferReference: " + targetTransferReference);
}

/** 启动脚本逻辑 */
function main(isDoTransfer) {
    // 设置坐标宽高
    // setScreenMetrics(720, 1640);
    console.log("w:" + device.width + " ,h:" + device.height);

    // 程序结束自动 隐藏控制台
    console.show(false);
    // --temp close
    if (false) {
        console.setMaxLines(15);
    }

    // 转账信息
    targetTransferAmount = "";
    targetTransferId = "";
    targetTransferAccount = "";
    targetTransferReference = "";

    // 是否需要重启app
    let isNeedRestartWalletApp = false;

    // 是否需要重启脚本
    let isNeedRestartScript = false;

    // 上传短信
    BaseSmsUtil.syncSmsData();

    console.log(Constant.UI_SDK_VERSION + "当前设备: " + Constant.getMtn());
    // sleep(5 * 1000);

    // airtel 钱包
    AirtelZmwAppOpen.openAirtelApp();

    // 上传短信 
    let lastSmsList = [];
    BaseSmsUtil.syncSmsData();
    sleep(2 * 1000);

    // 测试 --- temp close
    let testTimes = 0;

    while (true) {
        testTimes += 1;
        if (testTimes > 10) {
            console.log("======= 测试结束, 停止脚本");
            return;
        }
        console.log("======== testTimes:" + testTimes);
        // sleep(1000);

        // 清空转账信息
        cleanTransfer();

        // 页面状态
        let pageStatus = AirtelZmwPageUtil.doCheckPageStatus();
        let isLoginPage = pageStatus.isLoginPage;
        let isPinPage = pageStatus.isLoginPinPage;
        let isHomePage = pageStatus.isHomePage;
        let isAirtelMoneyPage = pageStatus.isAirtelMoneyPage;
        let isSendMoneyAccountInputPage = pageStatus.isSendMoneyAccountInputPage;
        let isBillListPage = pageStatus.isBillListPage;

        if (isBillListPage) {
            // 进入首页
            back();
            sleep(1000);

        } else if (isSendMoneyAccountInputPage) {
            // 进入首页
            back();
            sleep(1000);
        }

        // 判断是否在 momo 应用内
        let isInMomoApp = true;
        //AirtelZmwPageUtil.isInMomoApp();
        if (!isInMomoApp) {
            sleep(1 * 1000);
            home();
            sleep(2 * 1000);
            AirtelZmwAppOpen.openAirtelApp();

            // 上传短信
            BaseSmsUtil.syncSmsData();
            sleep(1 * 1000);

            // 清空控制台
            console.clear();
            continue;
        }

        // 上传短信
        BaseSmsUtil.syncSmsData();
        sleep(1 * 1000);

        // 获取脚本状态信息 -- temp close
        if (false) {
            let url = BaseApiUrl.checkOperStatus();
            let checkOperStatusParams = { phone: Constant.getMtn() }
            let checkOperStatusResult = BaseHttpUtil.sendPostSync(url, checkOperStatusParams)
            if (checkOperStatusResult !== null) {
                isNeedRestartWalletApp = checkOperStatusResult.momo || false;
                isNeedRestartScript = checkOperStatusResult.script || false;
            } else {
                isNeedRestartWalletApp = false;
                isNeedRestartScript = false;
            }
        }

        if (isNeedRestartScript) {
            sleep(1 * 1000);
            // 清空控制台
            console.clear();
            continue;
        }

        // 判断是否要重启app
        if (isNeedRestartWalletApp) {
            // 走关闭流程
            AirtelZmwAppOpen.closeAirtelApp();

            // 走重启流程
            AirtelZmwAppOpen.openAirtelApp();

            // 清空控制台
            console.clear();
            continue;

        } else {

            // 判断是否为登录-手机号页
            if (isLoginPage) {
                // 清空控制台
                // console.clear();

                // 走登录-手机号流程
                let doLoginResult = AirtelZmwFunAction.doLogin();
                if (doLoginResult) {
                    // 判断是否为 pin 页
                    isPinPage = AirtelZmwPageUtil.doOpenLoginPinPage();
                }
            }

            // 判断是否为登录-PIN页
            if (isPinPage) {
                // 清空控制台
                // console.clear();

                // 走登录-PIN流程
                let doPinResult = AirtelZmwFunAction.doPin();
                if (doPinResult) {
                    // 判断是否为 服务页
                    isHomePage = AirtelZmwPageUtil.doOpenHomePage();
                }
            }

            // 判断是否 服务页
            if (isHomePage) {
                // 点击 cash
                let doClickTabAirtelMoneyResult = AirtelZmwFunAction.doClickTabAirtelMoney();
                if (doClickTabAirtelMoneyResult) {
                    // 判断是否打开pin页
                    let doOpenLoginPinPageResult = AirtelZmwPageUtil.doOpenLoginPinPage();
                    if (doOpenLoginPinPageResult) {
                        // 走登录-PIN流程
                        let doPinResult = AirtelZmwFunAction.doPin();
                        if (doPinResult) {
                            // 判断是否为 首页
                            isAirtelMoneyPage = AirtelZmwPageUtil.doOpenTabAirtelMoneyPage();
                        }
                    }
                }
            }

            // 判断是否为首页
            if (isAirtelMoneyPage) {
                // 清空控制台
                //console.clear();

                // 获取转账信息
                cleanTransfer();
                // -- temp close 放款
                if (false) {
                    let url = BaseApiUrl.getMtnTransferAccount();
                    let mtnAccountParams = { num: "1", phone: Constant.getMtn() }
                    let mtnAccountResult = BaseHttpUtil.sendPostSync(url, mtnAccountParams)
                    if (mtnAccountResult !== null) {
                        if (mtnAccountResult.length > 0) {
                            initTransfer(mtnAccountResult[0]);
                        } else {
                            cleanTransfer();
                        }
                    } else {
                        cleanTransfer();
                    }

                    // 清空控制台
                    console.clear();

                    // 打印转账信息
                    printTransferLog();
                }
                // Test -- temp close 测试放款
                if (isDoTransfer) {
                    console.log("==== 测试放款");
                    initTransfer({
                        id: "id_TEST_T1",
                        amount: Constant.getAmount(),
                        mtn: Constant.TARGET_AIRTEL_ZMW_MOBILE,
                        reference: Constant.TARGET_AIRTEL_ZMW_REFERENCE
                    });
                    // 打印转账信息
                    printTransferLog();

                    // 判断是否需要转账
                    if (isValidTransfer()) {
                        console.log(Constant.UI_SDK_VERSION + "==== 需要执行转账");
                        // 走打开 Send Money 流程
                        // 点击 tab airtel money
                        let doClickTabAirtelMoneyResult = AirtelZmwFunAction.doClickTabAirtelMoney();
                        if (doClickTabAirtelMoneyResult) {
                            let doOpenTabAirtelMoneyPageResult = AirtelZmwPageUtil.doOpenTabAirtelMoneyPage();
                            // 判断是否打开 tab airtel money
                            if (doOpenTabAirtelMoneyPageResult) {
                                // 点击 send money
                                let doClickSendMoneyResult = AirtelZmwFunAction.doClickSendMoney();
                                if (doClickSendMoneyResult) {
                                    // 判断是否打开 send money
                                    let doOpenSendMoneyPageResult = AirtelZmwPageUtil.doOpenSendMoneyPage();
                                    if (doOpenSendMoneyPageResult) {
                                        // 输入 号码
                                        let doInputTargetAccountResult = AirtelZmwFunAction.doInputTargetAccount(targetTransferAccount);
                                        if (doInputTargetAccountResult) {
                                            // 判断是否识别到用户信息
                                            let doOpenInputTargetAmountPageResult = AirtelZmwPageUtil.doOpenInputTargetAmountPage();
                                            if (doOpenInputTargetAmountPageResult) {
                                                // 输入金额
                                                let doInputTargetAmountResult = AirtelZmwFunAction.doInputTargetAmount(targetTransferAmount);
                                                if (doInputTargetAmountResult) {
                                                    let doOpenSendMoneyConfirmPageResult = AirtelZmwPageUtil.doOpenSendMoneyConfirmPage();
                                                    // 判断是否打开转账确认页
                                                    if (doOpenSendMoneyConfirmPageResult) {
                                                        let doConfirmSendMoneyResult = AirtelZmwFunAction.doConfirmSendMoney();
                                                        if (doConfirmSendMoneyResult) {
                                                            // 输入pin码
                                                            let doOpenSendMoneyPasswordPageResult = AirtelZmwPageUtil.doOpenSendMoneyPasswordPage();
                                                            if (doOpenSendMoneyPasswordPageResult) {
                                                                let doInputPinResult = AirtelZmwFunAction.doInputSendMoneyPassword();
                                                                if (doInputPinResult) {
                                                                    // 判断是否转账成功
                                                                    let doOpenSendMoneyResultPageResult = AirtelZmwPageUtil.doOpenSendMoneyResultPage();
                                                                    // 判断是否为转账成功页
                                                                    if (doOpenSendMoneyResultPageResult.isSuccess) {
                                                                        // 点击返回
                                                                        let doClickTransferDoneAndGoBackResult = AirtelZmwFunAction.doClickTransferDoneAndGoBack();
                                                                        if (doClickTransferDoneAndGoBackResult) {
                                                                            console.log(Constant.UI_SDK_VERSION + "确认转账成功, 返回Send Money页");
                                                                        }
                                                                    }
                                                                    // 判断是否为转账失败页
                                                                    if (doOpenSendMoneyResultPageResult.isFail) {
                                                                        // 点击返回
                                                                        let doClickTransferFailAndGoBackResult = AirtelZmwFunAction.doClickTransferFailAndGoBack();
                                                                        if (doClickTransferFailAndGoBackResult) {
                                                                            console.log(Constant.UI_SDK_VERSION + "转账失败, 返回Send Money页");
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // 判断是否为 首页
            isHomePage = AirtelZmwPageUtil.doOpenHomePage();

            // 判断是否为首页
            if (isHomePage) {
                // 清空控制台
                // console.clear();

                let canCheckBillList = false;
                if ((!lastSmsList) || (lastSmsList.length === 0)) {
                    canCheckBillList = true;
                } else {
                    // 上传短信
                    let curSmsList = BaseSmsUtil.fetchSmsData();
                    console.log(Constant.UI_SDK_VERSION + "curSmsList条数: " + curSmsList.length);
                    console.log(Constant.UI_SDK_VERSION + "lastSmsList条数: " + lastSmsList.length);

                    for (checkBillIndex = 0; checkBillIndex < 3; checkBillIndex++) {
                        // 如果有新的短信，就去查流水
                        let isPaymentSmsChanged = BaseSmsUtil.isSmsListChangedForZmwAirtel(curSmsList, lastSmsList);

                        if (isPaymentSmsChanged) {
                            canCheckBillList = true;
                            lastSmsList = curSmsList;
                            console.log(Constant.UI_SDK_VERSION + "短信发生变动，需要重新查询流水")
                            break;
                        }

                        // 3秒后重新来查短信
                        curSmsList.length = 0;
                        curSmsList = null;
                        sleep(3000);
                        curSmsList = BaseSmsUtil.fetchSmsData();
                    }
                }

                if (canCheckBillList) {
                    // 清空控制台
                    // console.clear();

                    // 打开 tab more
                    let doClickTabMoreResult = AirtelZmwFunAction.doClickTabMore();
                    if (doClickTabMoreResult) {
                        let doOpenTabMorePageResult = AirtelZmwPageUtil.doOpenTabMorePage();
                        if (doOpenTabMorePageResult) {
                            // 点击 airtel money services
                            let doClickTabMoreAirtelMoneyServicesResult = AirtelZmwFunAction.doClickTabMoreAirtelMoneyServices();
                            if (doClickTabMoreAirtelMoneyServicesResult) {
                                let doOpenTabMoreAirtelMoneyServicesPageResult = AirtelZmwPageUtil.doOpenTabMoreAirtelMoneyServicesPage();
                                if (doOpenTabMoreAirtelMoneyServicesPageResult) {
                                    // 点击 transaction history
                                    let doClickTabMoreTransactionHistoryResult = AirtelZmwFunAction.doClickTabMoreTransactionHistory();
                                    if (doClickTabMoreTransactionHistoryResult) {
                                        // 打开流水页
                                        let doOpenBillListPageResult = AirtelZmwPageUtil.doOpenBillListPage();
                                        if (doOpenBillListPageResult) {
                                            // 读取流水页
                                            let doScanBillsForEachScreenResult = AirtelZmwFunAction.doScanBillsForEachScreen();
                                            if (doScanBillsForEachScreenResult) {
                                                sleep(2 * 1000);
                                                // 清空控制台
                                                // console.clear();
                                                // 上传短信
                                                BaseSmsUtil.syncSmsData();
                                                sleep(3 * 1000);
                                                continue;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            sleep(1 * 1000);

            // 最后都不能匹配成功，
            // 走关闭流程
            AirtelZmwAppOpen.closeAirtelApp();

            // 走重启流程
            AirtelZmwAppOpen.openAirtelApp();

            // 清空控制台
            console.clear();
        }
    }
}



